package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.DistanceUtil;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.dubbo.vo.UserLocationVo;
import com.tanhua.server.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class QuanZiService {

    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserService userService;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private QuanziMQService quanziMQService;

    @DubboReference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Value("${tanhua.default.publish.userId}")
    private Long defaultPublishUserId;


    /**
     * 查询好友动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public Object queryPublishList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);

        //查询好友的动态
        PageInfo<Publish> pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        pageResult.setItems(this.fillQuanZiVo(records));
        return pageResult;
    }

    private List<QuanZiVo> fillQuanZiVo(List<Publish> records) {
        Long userId = UserThreadLocal.get();
        //封装成QuanZiVo列表
        //查询动态发布人的用户信息列表
        Map<Long, UserInfo> userInfoMap = this.userInfoApi.queryMapByUserIdList(CollUtil.getFieldValues(records, "userId"));
        //设置集合,遍历好友动态
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(UserThreadLocal.get());
        for (Publish record : records) {
            String publishId = record.getId().toString();
            QuanZiVo quanZiVo = BeanUtil.toBeanIgnoreError(record, QuanZiVo.class);
            //获取自己发布动态的位置坐标  和发布用户的位置坐标
            if (ObjectUtil.isNotEmpty(userLocationVo)) {
                UserLocationVo publishUserLocationVo = this.userLocationApi.queryByUserId(record.getUserId());
                //计算距离
                double distance = DistanceUtil.getDistance(userLocationVo.getLongitude(), userLocationVo.getLatitude(), publishUserLocationVo.getLongitude(), publishUserLocationVo.getLatitude());
                quanZiVo.setDistance(distance / 1000 + "km" + publishUserLocationVo.getAddress()); //TODO 距离
            }
            if (ObjectUtil.isEmpty(userLocationVo)) {
                quanZiVo.setDistance("请开启定位");
            }
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated()))); //发布时间 如: 10分钟前
            quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(publishId))); //点赞数
            quanZiVo.setCommentCount(Convert.toInt(this.quanZiApi.queryCommentCount(publishId))); //TODO 评论数
            quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(publishId))); //TODO 喜欢数
            quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(userId, publishId) ? 1 : 0); //是否点赞（1是，0否）
            quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLove(userId, publishId) ? 1 : 0); //TODO 是否喜欢（1是，0否）

            //填充用户信息
            UserInfo userInfo = userInfoMap.get(record.getUserId());
            BeanUtil.copyProperties(userInfo, quanZiVo, "id");
            quanZiVo.setGender(userInfo.getSex().name().toLowerCase());

            quanZiVoList.add(quanZiVo);
        }
        return quanZiVoList;
    }

    /**
     * 发布动态
     *
     * @param textContent
     * @param location
     * @param latitude
     * @param longitude
     * @param multipartFile
     * @return
     */
    public Object savePublish(String textContent, String location, String latitude,
                              String longitude, MultipartFile[] multipartFile) {

        Publish publish = new Publish();
        publish.setUserId(UserThreadLocal.get());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLongitude(longitude);
        publish.setLatitude(latitude);
        publish.setMedias(new ArrayList<>());

        //上传图片
        if (ArrayUtil.isNotEmpty(multipartFile)) {
            for (MultipartFile file : multipartFile) {
                PicUploadResult uploadResult = this.picUploadService.upload(file);
                if (StrUtil.isNotEmpty(uploadResult.getName())) {
                    publish.getMedias().add(uploadResult.getName());
                }
            }
        }

        String result = this.quanZiApi.savePublish(publish);
        if (StrUtil.isNotEmpty(result)) {

            //发布成功后发送消息
            this.quanziMQService.publishMsg(result);

            return null;
        }

        return ErrorResult.builder().errCode("500")
                .errMessage("发布动态失败！").build();
    }

    /**
     * 查询推荐动态
     *
     * @return
     */
    public PageResult queryRecommendPublish(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();
        PageInfo<Publish> pageInfo = this.quanZiApi.queryRecommendPublishList(userId, page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
        //TODO 没有推荐,给出默认
            List<Publish> publishes = this.quanZiApi.quuerAllPublish(page, pageSize);
            pageResult.setItems(this.fillQuanZiVo(publishes));
            return pageResult;
        }
        pageResult.setItems(this.fillQuanZiVo(records));
        return pageResult;
    }

    /**
     * 点赞
     *
     * @param publishId
     * @return
     */
    public Long likeComment(String publishId) {
        Long userId = UserThreadLocal.get();
        //点赞
        Boolean result = this.quanZiApi.likeComment(userId, publishId);
        if (result) {
            //发送点赞成功的消息
            this.quanziMQService.likePublishMsg(publishId);

            //查询点赞数
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return 0L;
    }

    /**
     * 取消点赞
     *
     * @param publishId
     * @return
     */
    public Long disLikeComment(String publishId) {
        Long userId = UserThreadLocal.get();
        //取消点赞
        Boolean result = this.quanZiApi.disLikeComment(userId, publishId);
        if (result) {
            //发送取消点赞的消息
            this.quanziMQService.disLikePublishMsg(publishId);

            //查询点赞数
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return 0L;
    }

    /**
     * 自己的所有动态
     */
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(this.quanZiApi.queryUserCount(userId)); //TODO 数量

        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        pageResult.setItems(this.fillQuanZiVo(records));
        return pageResult;
    }

    public List<VisitorsVo> queryVisitorsList() {
        List<Visitors> visitorsList = this.visitorsApi.queryMyVisitor(UserThreadLocal.get());
        if (CollUtil.isEmpty(visitorsList)) {
            //没有访客
            return Collections.emptyList();
        }

        //获取用户id列表
        List<Object> visitorUserIdList = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        //查询访客的用户信息
        Map<Long, UserInfo> userInfoMap = this.userInfoApi.queryMapByUserIdList(visitorUserIdList);

        return visitorsList.stream().map(visitors -> {
            UserInfo userInfo = userInfoMap.get(visitors.getVisitorUserId());
            VisitorsVo visitorsVo = BeanUtil.toBeanIgnoreError(userInfo, VisitorsVo.class);
            visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
            return visitorsVo;
        }).collect(Collectors.toList());
    }

    /**
     * 动态喜欢
     *
     * @param publishId
     * @return
     */
    public Long LoveComment(String publishId) {
        //获取用户Id
        Long userId = UserThreadLocal.get();
        //用户点击喜欢
        Boolean result = this.quanZiApi.loveComment(userId, publishId);
        //成功发送喜欢成功的消息
        if (result) {
            this.quanziMQService.lovePublishMsg(publishId);
            //    查询喜欢数
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return 0L;
    }

    /**
     * 动态取消喜欢
     *
     * @param publishId
     * @return
     */
    public Long disLoveComment(String publishId) {
        //获取用户id
        Long userId = UserThreadLocal.get();
        //取消喜欢
        Boolean result = this.quanZiApi.disLoveComment(userId, publishId);
        if (result) {
            //   发送取消喜欢的消息
            this.quanziMQService.disLikePublishMsg(publishId);

            //    查询喜欢数
            this.quanZiApi.queryLoveCount(publishId);
        }
        return 0L;
    }

    /**
     * 查询评论列表
     *
     * @return
     */
    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {
        //设置分页参数
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(Convert.toInt(this.quanZiApi.queryCommentCount(publishId)));
        //获取用户id
        Long userId = UserThreadLocal.get();
        //查询评论
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentList(publishId, page, pageSize);
        //获取评论数据列表
        List<Comment> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        //获取评论用户id的列表
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        //根据评论用户id列表查询用户信息列表
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);
        ArrayList<CommentVo> result = new ArrayList<>();
        //封装成CommentVo返回
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            //设置评论
            commentVo.setContent(record.getContent());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "HH:mm"));
            commentVo.setId(record.getId().toString());
            //    点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));
            //    是否点赞
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(userId, commentVo.getId()) ? 1 : 0);
            for (UserInfo userInfo : userInfoList) {
                //评论人id和用户信息表id进行比较
                if (ObjectUtil.equals(record.getUserId(), userInfo.getUserId())) {
                    //设置头像
                    commentVo.setAvatar(userInfo.getLogo());
                    //设置昵称
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            result.add(commentVo);
        }
        pageResult.setItems(result);
        return pageResult;
    }

    /**
     * 发表评论
     *
     * @param publishId
     * @param content
     */
    public void saveComments(String publishId, String content) {
        this.quanZiApi.saveComment(UserThreadLocal.get(), publishId, content);
    }


    /**
     * 查询单条动态信息
     *
     * @param publishId
     * @return
     */
    public QuanZiVo queryById(String publishId) {
        //根据id查询动态
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (null == publish) {
            return null;
        }
        return this.fillQuanZiVo(Arrays.asList(publish)).get(0);
    }

    //com.tanhua.server.service.QuanZiService


}
